package opera;

import book.Book;
import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-07-14
 * Time: 14:24
 */
public class DelIOperation implements IOperation{
    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书...");
        System.out.print("请输入要删除的图书：");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();

        int currentSize = bookList.getUseSized();

        int pos = -1;//pos用来记录找到图书的下标
        //1.找到这本书
        int i = 0;
        for (; i < currentSize; i++) {
            Book book = bookList.getBook(i);
            if(book.getName().equals(name)){
                pos = i;
                break;
            }
        }

        if(i == currentSize){
            System.out.println("没有你要删除的图书");
            return;
        }

        //2.开始删除图书
        for (int j = pos; j < currentSize - 1; j++) {
            //j < currentSize - 1,如果只是currentSize,会越界
            //bookList[j] = bookList[j+1];
            Book book = bookList.getBook(j+1);//创建一个book对象，里面放book【j+1】
            bookList.setBook(j,book);
        }
        bookList.setUseSized(currentSize -1);
        System.out.println("删除成功");
    }
}
